package com.campus.server;

import com.campus.common.util.ConnectionPool;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;

public class ServerMain {
    // 创建固定大小的线程池
    private static final ExecutorService threadPool = Executors.newFixedThreadPool(50);

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务器启动，等待客户端连接...");

        // 添加关闭钩子，确保程序退出时释放资源
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("正在关闭服务器...");
            threadPool.shutdown();
            ConnectionPool.shutdown();
        }));

        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("客户端连接：" + socket.getInetAddress());

            // 使用线程池处理客户端请求，而不是直接创建新线程
            threadPool.execute(new ClientHandler(socket));
        }
    }
}